import isEmpty from 'lodash/isEmpty';
import { Menu, Modal } from 'antd';
import {
  WeaSearchGroup,
  WeaDropdown,
  WeaTag,
  WeaFormItem,
  WeaLocaleProvider,
} from 'ecCom';
import { WeaSwitch } from 'comsMobx';
import CoworkConstant from './CoworkConstant';

const getLabel = WeaLocaleProvider.getLabel;

export const getNewFiels = (fields = {}) => {
  let params = {};
  if (!isEmpty(fields)) {
    for (let key in fields) {
      params[fields[key].name] = fields[key].value;
    }
  }
  return params;
};

// 用于获取高级搜索中的表单控件
// 一定要先初始化initFormFields表单对象
// 用于获取高级搜索中的表单控件
export const getSearchs = (form, datas, onEnterSearch) => {
  const { isFormInit } = form;
  const enterSearch = () => {
    if (onEnterSearch && typeof onEnterSearch === 'function') {
      onEnterSearch();
    }
  };
  let group = [];
  const formParams = form.getFormParams();
  isFormInit &&
    datas &&
    datas.map((c) => {
      let items = [];
      c.items.map((fields) => {
        items.push({
          com: (
            <WeaFormItem
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaFormItem@ocgv4h@${fields.domkey[0]}`}
              label={`${fields.label}`}
              labelCol={{ span: `${fields.labelcol}` }}
              viewAttr={fields.viewAttr}
              wrapperCol={{ span: `${fields.fieldcol}` }}
            >
              <WeaSwitch
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaSwitch@q6xvz8@${fields.domkey[0]}`}
                fieldConfig={fields}
                form={form}
                formParams={formParams}
                onEnterSearch={enterSearch}
              />
            </WeaFormItem>
          ),
          colSpan: 1,
        });
      });
      group.push(
        <WeaSearchGroup
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaSearchGroup@3s04l3@searchgroup`}
          needTigger={true}
          title={c.title}
          showGroup={c.defaultshow}
          items={items}
        />,
      );
    });
  return group;
};

// 打开查看某个协作的页面
export const getViewCoworkUrl = (coworkId) => {
  let url = `/spa/cowork/static/index.html#/cowork/${coworkId}`;
  return url;
};

// 打开查看某个协作具体楼层的页面
export const getViewCoworkOfFloorNnmUrl = (coworkId, floorNum) => {
  let url = `/spa/cowork/static/index.html#/cowork/${coworkId}/${floorNum}`;
  return url;
};

export const createReplyBottomAtt = (icon, label, list, isAttach = false) => {
  if (!list || list.length == 0) return null;
  return (
    <div className="cowork-att-list">
      <div className="cowork-att-content">
        <div title={label}>
          <i className={icon} />
        </div>
        <ul>
          {list.map((item) => {
            if (isAttach) {
              return (
                <li>
                  <a onClick={() => window.open(item.url)} title={item.name}>
                    {item.name}
                    <span
                      onClick={(e) => {
                        e.stopPropagation();
                        window.open(item.downUrl);
                      }}
                    >
                      [ 下载({item.downName}) ]
                    </span>
                  </a>
                </li>
              );
            }
            return (
              <li>
                <a href={item.url} target="_blank">
                  {item.name}
                </a>
              </li>
            );
          })}
        </ul>
      </div>
    </div>
  );
};
export const dateFormat = (date, fmt = 'yyyy-MM-dd') => {
  if (date && fmt) {
    let _this = date;
    const type = Object.prototype.toString.call(date);
    if (type == '[object String]') {
      let dateArray = date.split(' '),
        d1 = dateArray[0].split('-'),
        d2 = dateArray[1] ? dateArray[1].split(':') : [];
      _this = new Date(
        (d1[0] || 0) * 1,
        (d1[1] || 0) * 1 - 1,
        (d1[2] || 0) * 1,
        (d2[0] || 0) * 1,
        (d2[1] || 0) * 1,
        (d2[2] || 0) * 1,
      );
    } else if (type == '[object Date]') {
    } else {
      return '';
    }
    let o = {
      'M+': _this.getMonth() + 1, // 月份
      'd+': _this.getDate(), // 日
      'h+': _this.getHours() % 12 == 0 ? 12 : _this.getHours() % 12, // 小时
      'H+': _this.getHours(), // 小时
      'm+': _this.getMinutes(), // 分
      's+': _this.getSeconds(), // 秒
      'q+': Math.floor((_this.getMonth() + 3) / 3), // 季度
      S: _this.getMilliseconds(), // 毫秒
    };
    let week = {
      0: '\\u65e5',
      1: '\\u4e00',
      2: '\\u4e8c',
      3: '\\u4e09',
      4: '\\u56db',
      5: '\\u4e94',
      6: '\\u516d',
    };
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        `${_this.getFullYear()}`.substr(4 - RegExp.$1.length),
      );
    }
    if (/(E+)/.test(fmt)) {
      let weekStr =
        (RegExp.$1.length > 1
          ? RegExp.$1.length > 2
            ? '\\u661f\\u671f'
            : '\\u5468'
          : '') + week[`${_this.getDay()}`];
      fmt = fmt.replace(
        RegExp.$1,
        Utils.GB2312UnicodeConverter.ToGB2312(weekStr),
      );
    }
    for (let k in o) {
      if (new RegExp(`(${k})`).test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length == 1 ? o[k] : `00${o[k]}`.substr(`${o[k]}`.length),
        );
      }
    }
    return fmt;
  }
  return '';
};

export const imgZoom = (dom, parentSelector) => {
  let imgList = jQuery(`${parentSelector} img`, dom);
  imgList.each((index, img) => {
    let $img = $(img);
    if ($img.attr('resize')) {
      return;
    }
    if ($img.parents('.ui-coomixPic').length > 0) {
      return;
    }
    $img
      .css({ 'max-width': '400px', 'max-height': '400px' })
      .attr('resize', 1)
      .coomixPic({
        path: '/blog/js/weaverImgZoom/images',
        preload: true,
        blur: true,
        left: getLabel(26921, '向左转'),
        right: getLabel(26922, '向右转'),
        source: getLabel(26923, '查看原图'),
        hide: getLabel(26985, '收起'),
      });
  });
};

export const createAttachLi = item => (
  <li className="cowork-accessory-item">
    {item.docextendname && item.docextendname == 'html' && (
      <em className="icon-coms-html2" />
    )}
    {item.docextendname && item.docextendname == 'doc' && (
      <em className="icon-coms-word2" />
    )}
    {item.docextendname && item.docextendname == 'docx' && (
      <em className="icon-coms-word2" />
    )}
    {item.docextendname && item.docextendname == 'wps' && (
      <em className="icon-coms-word2" />
    )}
    {item.docextendname && item.docextendname == 'jpeg' && (
      <em className="icon-coms-pic2" />
    )}
    {item.docextendname && item.docextendname == 'png' && (
      <em className="icon-coms-pic2" />
    )}
    {item.docextendname && item.docextendname == 'jpg' && (
      <em className="icon-coms-pic2" />
    )}
    {item.docextendname && item.docextendname == 'xlsx' && (
      <em className="icon-coms-currency2" />
    )}
    {item.docextendname && item.docextendname == 'xls' && (
      <em className="icon-coms-currency2" />
    )}
    {item.docextendname && item.docextendname == 'zip' && (
      <em className="icon-coms-rar2" />
    )}
    {item.docextendname && item.docextendname == 'excel' && (
      <em className="icon-coms-excel2" />
    )}
    {item.docextendname && item.docextendname == 'pdf' && (
      <em className="icon-coms-pdf2" />
    )}
    {item.docextendname && item.docextendname == 'ppt' && (
      <em className="icon-coms-ppt2" />
    )}
    <a
      className="item-a"
      onClick={() => window.open(item.url)}
      title={item.name}
    >
      {item.name}
    </a>
    <i
      className="icon-coms-download"
      onClick={(e) => {
        e.stopPropagation();
        window.open(item.downUrl);
      }}
    />
    <span>{item.downName}</span>
  </li>
);

// 灰度算法
export const isColorDark = (colorHex, threshold) => {
  if (!colorHex || typeof colorHex != 'string') {
    return false;
  }
  if (colorHex.indexOf('#') == 0) {
    colorHex = colorHex.substring(1, colorHex.length);
  }
  let temp = colorHex.split('');
  let R,
G,
B;
  // #abcdef
  if (temp.length == 6) {
    R = temp[0] + temp[1];
    G = temp[2] + temp[3];
    B = temp[4] + temp[5];
  }
  // #abc
  else if (temp.length == 3) {
    R = temp[0] + temp[0];
    G = temp[1] + temp[1];
    B = temp[2] + temp[2];
  } else {
    return false;
  }
  let Gray =
    parseInt(R, 16) * 0.299 + parseInt(G, 16) * 0.587 + parseInt(B, 16) * 0.114;
  if (Gray < (threshold || 125)) {
    return true;
  }
  return false;
};

export const createMarkMenu = (labelList, onMark) => (
  <Menu
    ecId={`${(this && this.props && this.props.ecId) || ''}_Menu@28y2sa`}
    className="wea-cowork-dropdown-menu"
    onClick={onMark}
  >
    <Menu.Item
      ecId={`${(this && this.props && this.props.ecId) || ''}_MenuItem@kt01k3`}
      key="read"
    >
      {getLabel(25425, '已读')}
    </Menu.Item>
    <Menu.Item
      ecId={`${(this && this.props && this.props.ecId) || ''}_MenuItem@laubq4`}
      key="unread"
    >
      {getLabel(83697, '未读')}
    </Menu.Item>
    <Menu.Divider
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_MenuDivider@naxotu`}
    />
    <Menu.Item
      ecId={`${(this && this.props && this.props.ecId) || ''}_MenuItem@944v0b`}
      key="important"
    >
      {getLabel(382626, '标星')}
    </Menu.Item>
    <Menu.Item
      ecId={`${(this && this.props && this.props.ecId) || ''}_MenuItem@aeg4av`}
      key="normal"
    >
      {getLabel(382669, '取消标星')}
    </Menu.Item>
    <Menu.Divider
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_MenuDivider@2p9as1`}
    />
    <Menu.Item
      ecId={`${(this && this.props && this.props.ecId) || ''}_MenuItem@gdf5c2`}
      key="hidden"
    >
      {getLabel(16636, '隐藏')}
    </Menu.Item>
    <Menu.Item
      ecId={`${(this && this.props && this.props.ecId) || ''}_MenuItem@ll9khv`}
      key="show"
    >
      {getLabel(25424, '取消隐藏')}
    </Menu.Item>
    <Menu.Divider
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_MenuDivider@6v8js3`}
    />
    <Menu.Item
      ecId={`${(this && this.props && this.props.ecId) || ''}_MenuItem@82u4nd`}
      key="tag"
    >
      {getLabel(176, '标签')}...
      <span className="icon-coms-Flow-setting" />
    </Menu.Item>
    {labelList.length > 0 &&
      labelList
        .filter(label => label.labelType != 'typePlate')
        .map(label => (
          <Menu.Item
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_MenuItem@j4z8zy@${label.id}`}
            key={label.id}
            className="wea-cowork-tag-menu-item"
          >
            <WeaTag
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaTag@bdzx3o@${label.id}`}
              className="setable-label"
              color={label.labelColor}
            >
              {label.labelName}
            </WeaTag>
          </Menu.Item>
        ))}
    <Menu.Divider
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_MenuDivider@366915`}
    />
    <Menu.Item
      ecId={`${(this && this.props && this.props.ecId) || ''}_MenuItem@4c06hs`}
      key="deleteAll"
    >
      {getLabel(31219, '取消所有标签')}
    </Menu.Item>
  </Menu>
);

export const createSortMenu = (sortKey, onSort) => (
  <WeaDropdown
    ecId={`${(this && this.props && this.props.ecId) || ''}_WeaDropdown@vhl2yp`}
    datas={CoworkConstant.sortMenu()}
    onSelect={onSort}
    currentKey={sortKey}
  />
);

export const onCheck = (form, func) => {
  form.validateForm().then((f) => {
    if (f.isValid) {
      func && typeof func == 'function' && func();
    } else {
      f.showErrors();
    }
  });
};

// 信息确认
export const doConfirm = (content, func) => {
  // 确认信息， 方法， 方法参数
  Modal.confirm({
    title: `${getLabel(131329, '信息确认')}`,
    content,
    okText: `${getLabel(382958, '确定')}`,
    cancelText: `${getLabel(31129, '取消')}`,
    onOk: () => func && func(),
  });
};

export const richfilter = (data, keyWords, color) => {
  // 高亮显示
  let newData = data,
    bgColor = color || '#ff9632',
    newKeyWords = `<span style='background-color: ${bgColor};'>${keyWords}</span>`,
    nodeNum = -1,
    charNum = -1,
    keys = new RegExp(keyWords, 'g'),
    nodes = new RegExp('<.*?>', 'ig'), // 匹配html元素
    chars = new RegExp('&.*?;', 'ig'), // 匹配转义字符
    oldNodes = newData.match(nodes), // 存放html元素的数组
    oldChars = newData.match(chars); // 存放转义字符的数组

  newData = newData.replace(nodes, '{~}'); // 替换html标签
  newData = newData.replace(chars, '{~~}'); // 替换转义字符
  newData = newData.replace(keys, newKeyWords); // 替换key
  newData = newData.replace(/{~}/g, () => {
    // 恢复html标签
    nodeNum++;
    return oldNodes[nodeNum];
  });
  newData = newData.replace(/{~~}/g, () => {
    // 恢复html标签
    charNum++;
    return oldChars[charNum];
  });
  return newData;
};

export const replaceFun = v =>
  v.replace(
    /<a[^>]*[^>]*>(.*?)<\/a>/g,
    m => `<a target="_blank" ${m.slice(3)}`,
  );
